﻿using Abp.Json;
using ARchGL.Platform.Configuration;
using IdentityModel.Client;
using System;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace ARchGL.Platform.Sessions
{
    /// <summary>
    /// 刷新 SpiderBIM AccessToken 服务
    /// </summary>
    public static class RefreshTokenService
    {
        public static string AccessToken { get; private set; }
        public static TokenResponse TokenResponse { get; set; }

        /// <summary>
        /// 刷新 SpiderBIM AccessToken
        /// </summary>
        /// <param name="config"></param>
        public static void RefreshToken(this SpiderConfigOptions config)
        {
            TokenResponse = GetAuthorizeAsync(config).Result;
            AccessToken = TokenResponse?.AccessToken;
        }

        /// <summary>
        /// 获取带有 Bearer 前缀的 AccessToken
        /// </summary>
        /// <returns></returns>
        public static string GetAccessToken()
        {
            Console.WriteLine($"\r\n############################## SpiderBIM  使用的Token {AccessToken}");
            return new AuthenticationHeaderValue("Bearer", AccessToken).ToString();
        }

        /// <summary>
        /// 统一获取 SpiderBIM token的通用方法
        /// </summary>
        /// <param name="config">配置信息</param>
        /// <returns></returns>
        private static async Task<TokenResponse> GetAuthorizeAsync(SpiderConfigOptions config)
        {
            var tokenClient = new TokenClient(config.TokenUrl, config.ClientId, config.ClientSecret);
            var tokenResponse = await tokenClient.RequestResourceOwnerPasswordAsync(config.Username, config.Password, config.Scope);
            if (tokenResponse.IsError)
            {
                Console.WriteLine("获取 SpiderToken 异常：" + tokenResponse.ToJsonString());
                return null;
            }
            return tokenResponse;
        }
    }
}
